import React from 'react';
import { useThrottleFn } from 'ahooks';
import styles from './index.less';

export default (props) => {
  const { pageWidth = 0, thumbWidth = 0, onLeft = () => {} } = props;
  const thumbRef = React.useRef(null);
  const menuWidth = React.useMemo(() => document.body.clientWidth - pageWidth, [pageWidth]);
  const [dragging, setDragging] = React.useState(false);
  const [state, setState] = React.useState({
    dragging: false,
    direction: '', // 移动方向
    innerL: 0, // 鼠标距盒左边距离
    left: 0, // 移动距离
    startL: 0, // 开始位置
  });

  const { run } = useThrottleFn((v) => onLeft?.(v), { wait: 100 });

  /** 滑块 evenet */
  const onMove = (e) => {
    const curL = e.clientX - menuWidth;
    const leftRange = [0, pageWidth - thumbWidth];
    // 方向
    let _direct = '';
    if (curL > state.startL) {
      _direct = 'right';
    } else if (curL < state.startL) {
      _direct = 'left';
    }
    // 边界
    let left = curL - state.innerL;
    if (left > leftRange[1]) {
      left = leftRange[1];
      if (_direct === 'left') {
        state.innerL = curL - thumbRef.current.offsetLeft;
      }
      if (_direct === 'right') {
        state.startL = curL;
      }
    } else if (left < leftRange[0]) {
      left = leftRange[0];
      if (_direct === 'left') {
        state.startL = curL;
      }
      if (_direct === 'right') {
        state.innerL = curL - thumbRef.current.offsetLeft;
      }
    }
    state.direction;
    state.left = left;
    setState({ ...state });
    run(left);
  };

  const onStart = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragging(true);
    state.startL = e.clientX - menuWidth;
    state.innerL = state.startL - thumbRef.current.offsetLeft;
    setState({ ...state });
    document.onmousemove = onMove;
  };

  const onEnd = () => {
    setDragging(false);
    state.direction = '';
    setState({ ...state });
    document.onmousemove = null;
  };

  return (
    <div className={styles.thumbWrap} onMouseLeave={onEnd}>
      <div
        ref={thumbRef}
        className={[styles.thumb, dragging ? styles.dragging : ''].join(' ')}
        style={{ width: `${thumbWidth}px`, left: `${state.left}px` }}
        onMouseDown={onStart}
        onTouchStart={onStart}
        onMouseUp={onEnd}
        onTouchEnd={onEnd}
      />
    </div>
  );
};
